<?php
/**
 * This is a controller for Page.
 *
 * This controller would be responsible for applying actions in classical admin area.
 * it could be any changes concerned mass applying
 * @author Pavel Savchuk
 */

class Backend_PageController extends RCMS_Core_BaseController {

/**
 * Special parser that creates seo for this site.
 *
 * @var RCMS_Object_Parser_SeoParser
 */
	protected $_seoParser = null;

	protected $_websitePath = '';

	protected $_previewPath = '';

	protected $_previewFolderName = '';

	protected $_pathTmp = '';

	/**
	 * Preview path for page's image
	 *
	 * @var string
	 */
	protected $_savePathPreviewPage;

	public function init() {
		parent::init();
        $this->_checkLogin(array('stat'));
		$this->_model             = new Backend_PageModel();
		$this->_seoParser         = new RCMS_Object_Parser_SeoParser();
		$this->_websitePath       = $this->_config->website->website->path;
		$this->_pathTmp           = $this->_websitePath . 'tmp/';
		$this->_previewPath       = $this->_websitePath . $this->_config->page->page->preview_path;
		$this->_previewFolderName = $this->_config->page->page->preview_folder;
	}

	/**
	 * Init form data for a page
	 * 
	 * @return RCMS_Form_PageForm
	 */
	public function initDataForCreatePageForm() {
		$pageForm          = new RCMS_Form_PageForm();
		$categories		   = $this->_addSignToProtectedNames($this->_model->selectAllCategories());
		unset($categories[-1]);
		$categories        = array('-1' => 'Select a category') + $categories;
		$pageForm->getElement('pageselectcategory')->setMultiOptions($categories);
		$pageForm->getElement('selectmenu')->setMultiOptions($categories);
		$pageForm->getElement('selectmenu')->setMultiOptions($this->generateShowInMainMenuSelectData());
		return $pageForm;
	}

	public function draftlistAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$draftPagesViewData = array();
		$draftCategoryId = $this->_model->selectCategoryIdByName(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
		$draftPagesData = $this->_model->selectDraftPagesUrls($draftCategoryId);
		if(is_array($draftPagesData)) {
			foreach($draftPagesData as $draftPageData) {
				$draftPagesViewData[][$draftPageData['pageNavName']] = $draftPageData['pageUrl'];
			}
			$this->view->draftData = $draftPagesViewData;
		}
		else {
			$this->view->draftUrls = '';
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * This method is an action which is responsible for adding new page
	 *
	 * @return void
	 */
	public function addpageAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_checkDirs();
		$this->view->pageForm = $this->initDataForCreatePageForm();
		if($this->getRequest()->isPost()) {
			if($this->view->pageForm->isValid($this->getRequest()->getParams())) {
				$pageData = $this->view->pageForm->getValues();
				$pageData['owner'] = unserialize($this->_session->currentUser)->getId();
				$isCategory        = $pageData['iscategory'];
				$categoryId        = $pageData['pageselectcategory'];
				$imageName         = $pageData['image_name'];
				$imagePath         = $pageData['image_path'];
				$navigationName    = $pageData['nav_name'];
				$showInMenu        = $pageData['selectmenu'];
				$url               = $this->proccessUrl($pageData['url']);
				$targetedKeyPhrase = empty($pageData['targetedKeyPhrase']) ? $pageData['url'] : trim($pageData['targetedKeyPhrase']);
				if($isCategory && $this->_model->selectCategoryByName($navigationName)) {
					$this->view->categoryExists = true;
				}
				if($this->_model->selectUrl($url)) {
					$this->view->urlExists = true;
				}
				//check if a page is with such navigation name is already in database
				if($this->_model->selectPageByNavigationName($navigationName)) {
					if(!isset($this->_session->pageExists)) {
						$this->_session->pageExists = true;
						$this->view->pageExists = true;
					}
					else {
						unset($this->_session->pageExists);
						$this->view->pageExists = false;
					}
				}
				//if there are no errors
				if(!$this->view->categoryExists && !$this->view->pageExists && !$this->view->urlExists) {
					if($pageData) {
						$pageObj = new RCMS_Object_Page_Page();
						$pageData = $this->_addOptionsToPageData($pageData);
						$pageObj->loadObjectFromArray($pageData);
						//if page marked as category than we insert new category
						//else we adjust page to existed category
						if($isCategory)
							$lastCategoryId = $this->_model->insertNewCategory($navigationName);
						else {
							$lastCategoryId =  $this->_model->insertNewCategory($navigationName, $categoryId);
							if($this->_isProtected($categoryId)) {
								$pageObj->setProtected(true);
							}
						}
						$pageObj->setCategoryId($lastCategoryId);
						$pageObj->setShowInMenu($showInMenu);
						//if template was not selected
						if ($pageObj->getTemplateId() == 0) {
							//put an error about it
							$this->view->errorElements = $this->processErrors(array('template' => array('isEmpty' => true)));
							$this->_helper->viewRenderer->setNoRender(true);
							echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
							return;
						}
						//process image if it was uploaded.
						$pageId = $pageObj->save();
						if($pageId) {
							if(!empty ($imageName)) {
								$this->_proccessPageImage($imageName, $pageId, $imagePath, $url);
							}
							$featuredIdsArray = explode(':', $this->view->pageForm->getElement('featured_ids')->getValue());
							if(!empty ($featuredIdsArray)) {
								foreach ($featuredIdsArray as $fa) {
									if(intval($fa)) {
										$this->_model->insertPageHasFa($pageId,$fa);
									}
								}
							}
							$this->_seoParser->createSiteMapFile();
							$this->view->redirect = $this->getWebSiteUrl() . $url . '.html';
						}
					}
				}
			}
			else {
				$this->view->errorElements = $this->processErrors($this->view->pageForm->getMessages());
			}
		}
		$this->_helper->viewRenderer->setNoRender(true);
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));

	}

	private function _isProtected($categoryId) {
		return $this->_model->isProtected($categoryId);
	}

	/**
	 * @method  Edit page action
	 * @return Void
	 */
	public function editpageAction() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_checkDirs();
		$pageId = $this->getRequest()->getParam('pageId');
		if(intval($pageId)) {
			$pageObj  = new RCMS_Object_Page_Page($pageId);
			$templateObj  = new RCMS_Object_Template_Template($pageObj->getTemplateId());
			$this->_session->oldPageUrl = urldecode($pageObj->getUrl());
			$pageImageObj = $this->_model->selectPageImage($pageId);
			if($pageObj->getCategoryId() > 0) {
				$category = $this->_model->selectCategoryById($pageObj->getCategoryId());
				if($category) {
					$categoryParent = $category->id_parent;
				}
				else {
					$categoryParent = -1;
				}
			}
			/*getting array of Featured areas*/
			$featuredResult = $this->_model->selectFeaturedAreasByPageId($pageId);
			$this->view->faLinkMessage = (sizeof($featuredResult) > 0) ? 'Yes, ' . sizeof($featuredResult) . ' Times.' : 'Not yet.' ;
			if($featuredResult) {
				$pageFeaturedOrder = array();
				foreach ($featuredResult as $fa) {
					$featuredAreasArray[] = $fa['fa_id'];
					$pageFeaturedOrder[$fa['fa_id']] = $fa['order'];
				}
				$featuredAreasStr = implode(':', $featuredAreasArray);
				$featuredAreasStr .= ':';
			}
           /*end getting array of Featured areas*/
		}
		$pageForm = $this->initPageEditForm($pageObj);
		$pageForm->getElement('featured_ids')->setValue(isset($featuredAreasStr) ? $featuredAreasStr : '');
		$pageForm->getElement('image_name')->setValue(($pageImageObj) ? $pageImageObj->name : '');
		$this->view->pageForm      = $pageForm;
		$this->view->is404         = $pageObj->getIs404Page();
		$this->view->optString     = $this->_generateOptionsString($pageObj);
		$this->view->isProtected   = $pageObj->getProtected();
		$this->view->memLanding    = $pageObj->getMemLandig();
		$this->view->prodBrandLand = $pageObj->getProdBrandLand();
		$this->view->prodCatLand   = $pageObj->getProdCatLand();
		
		if($this->getRequest()->isPost()) {
			$oldCatagoryId     = $pageObj->getCategoryId();
			$oldNavegationName = $pageObj->getNavName();
			$pageOrder         = $pageObj->getOrder();
			$staticOrder       = $pageObj->getStaticOrder();
			//is this category has pages and we trying to make it just regular page.
			$hasPages = false;
			if($this->view->pageForm->isValid($this->getRequest()->getParams())) {
				$pageData              = $this->view->pageForm->getValues();
				$pageData['id']        = $pageObj->getId();
				$pageData['protected'] = $pageObj->getProtected();
				$isCategory            = $pageData['iscategory'];
				$categoryId            = $pageData['pageselectcategory'];
				$imageName             = $pageData['image_name'];
				$imagePath             = $pageData['image_path'];
				$navigationName        = trim($pageData['nav_name']);
				$showInMenu            = $pageData['selectmenu'];
				$url                   = $this->proccessUrl($pageData['url']);
				$targetedKeyPhrase     = empty($pageData['targetedKeyPhrase']) ? $pageData['url'] : trim($pageData['targetedKeyPhrase']);
				if(!$isCategory) {
					if($this->_model->selectAllCategories($oldCatagoryId)) {
						$hasPages = true;
					}
				}
				$urlExists = false;
				if($this->_model->selectUrl($url) && $pageObj->getUrl() != $url) {
					$this->view->urlExists = true;
					$urlExists = true;
				}
				$navigationNameExists = false;
				if($this->_model->selectPageByNavigationName($navigationName) && $pageObj->getNavName() != $navigationName) {
					if(!isset($this->_session->navigationNameExists[$pageObj->getId()])) {
						$this->_session->navigationNameExists[$pageObj->getId()] = true;
						$this->view->navigationNameExists = true;
						$navigationNameExists = true;
					}
					else {
						unset($this->_session->navigationNameExists[$pageObj->getId()]);
						$this->view->navigationNameExists = false;
						$navigationNameExists = false;
					}
				}
				//check if there is a page with such a navigation name in the database?
				//and new navigation name was not changed
				if(!$hasPages && !$urlExists && (trim(strtolower($navigationName)) == trim(strtolower($pageObj->getNavName())) || !$navigationNameExists)) {
					if($pageData) {
						$pageData = $this->_addOptionsToPageData($pageData);
						$pageObj->loadObjectFromArray($pageData);
						$pageObj->setOrder(!empty($pageOrder) ? $pageOrder : '');
						$pageObj->setStaticOrder(!empty($staticOrder) ? $staticOrder : '');
						//if page marked as no category
						if(!$isCategory) {   //if there was no category with such a name before
							if(!$this->_model->selectCategoryByName(trim($pageObj->getNavName()))) {
								if($this->_isProtected($categoryId)) {
									$pageObj->setProtected(true);
								}
								$this->_model->updateCategory(trim($pageObj->getNavName()), $oldCatagoryId, $categoryId);
								$pageObj->setCategoryId($oldCatagoryId);
							}
							else {//if name not changed then error
								if(strtolower($pageObj->getNavName()) != strtolower(trim($oldNavegationName))) {
									$this->view->categoryExists = true;
								}
								else {   //update category name with saving hierarcy level
									$this->_model->updateCategory(trim($pageObj->getNavName()), $oldCatagoryId, $categoryId);
									$pageObj->setCategoryId($oldCatagoryId);
								}
							}
						}
						else {//if there was no category with such name before
							if(!$this->_model->selectCategoryByName(trim($pageObj->getNavName()))) {
								$this->_model->updateCategory(trim($pageObj->getNavName()), $oldCatagoryId);
								$pageObj->setCategoryId($oldCatagoryId);
							}
							else {
								if(strtolower(trim($pageObj->getNavName())) != strtolower(trim($oldNavegationName))) {
									$this->view->categoryExists = true;
								}
								else {
									$pageObj->setCategoryId($oldCatagoryId);
								}
							}
						}
						if(!$this->view->categoryExists) {
							$pageObj->setShowInMenu($showInMenu);
							$result = $pageObj->save();
							if($result) {
								if(!empty ($imageName)) {
									$this->_proccessPageImage($imageName, $pageObj->getId(), $imagePath, $pageObj->getUrl(), $pageImageObj->name);
								}
								$featuredIds = $pageForm->getElement('featured_ids')->getValue();
								$this->_model->deleteFeaturedAreasByPageId($pageId);
								if(!empty($featuredIds)) {
									$featuredIdsArray = explode(":", $featuredIds);
									foreach ($featuredIdsArray as $fa) {
										if(intval($fa)) {
											$this->_model->insertPageHasFa($pageId, $fa, ($pageFeaturedOrder[$fa] ? $pageFeaturedOrder[$fa] : 0));
										}
									}
								}
								$this->_seoParser->chainSyncOnUpdate($this->_session->oldPageUrl, $pageObj->getUrl(), $pageObj->getH1Tag(), $pageObj->getId());
								$this->_seoParser->createSiteMapFile();
								$this->view->redirect = $this->getWebSiteUrl().$pageObj->getUrl() . '.html';
							}
						}
					}
				}
				else {
					if($hasPages) {
						$this->view->hasPages = $hasPages;
					}
					if(!(trim(strtolower($navigationName)) == trim(strtolower($pageObj->getNavName()))) || !$this->_model->selectPageByNavigationName($navigationName)) {
						$this->view->pageExists = $navigationNameExists;
					}
				}
			}
			else {
				$this->view->errorElements = $this->processErrors($this->view->pageForm->getMessages());
			}
		}
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

	private function _checkDirs() {
		if(!is_dir($this->_websitePath . $this->_previewFolderName)) {
			@mkdir($this->_websitePath . $this->_previewFolderName);
		}
		if(!is_dir($this->_pathTmp)) {
			@mkdir($this->_pathTmp);
		}
	}

	private function _proccessPageImage($imageName, $pageId, $imagePath, $url, $oldName = '') {
		$oldImagePath = $this->_websitePath . $imagePath;
		$explodedImageName = explode('.', $imageName);
		$newImageFileName = RCMS_Tools_FilesystemTools::normalize(RCMS_Tools_FilesystemTools::trimInternalSpaces($url), $pageId) . '.' . $explodedImageName[1];
		$newImagePath = $this->_previewPath . $newImageFileName;
		$this->view->pageForm->getElement('image_name')->setValue($newImageFileName);
		if($oldName) {
			$explodedImgName = explode('.', $imageName);
			if(preg_match('/^[0-9]+$/', $explodedImgName[0])) {
				@unlink($this->_previewPath . RCMS_Tools_FilesystemTools::normalize($oldName), $pageId);
				clearstatcache();
			}
			else {
				@rename($this->_previewPath . $imageName, $newImagePath);
			}
		}
		@copy($oldImagePath, $newImagePath);
		$updResult = $this->_model->updatePagePreview($newImageFileName, $pageId, $this->_previewFolderName . '/' . $newImageFileName);
		if(!$updResult) {
			$this->_model->insertPagePreview($newImageFileName, $pageId, $this->_previewFolderName . '/' . $newImageFileName);
		}
		RCMS_Tools_FilesystemTools::removeSWFUploadTempFiles();
	}

	/**
	 *@method Init data for editing page form
	 *@param RCMS_Object_Page_Page $pageObj
	 *@return RCMS_Form_PageForm $pageForm
	 */
	private function initPageEditForm(RCMS_Object_Page_Page $pageObj) {
		if($pageObj instanceof RCMS_Object_Page_Page) {
			$pageForm = new RCMS_Form_PageForm();
			$pageForm->getElement('page_id')->setValue($pageObj->getId());
			$pageForm->getElement('h1')->setValue($pageObj->getH1Tag());
			$pageForm->getElement('header_title')->setValue($pageObj->getHeaderTitle());
			$pageForm->getElement('url')->setValue(urldecode(urldecode($pageObj->proccessUrl($pageObj->getUrl()))));
			$pageForm->getElement('nav_name')->setValue($pageObj->getNavName());
			$pageForm->getElement('meta_description')->setValue($pageObj->getMetaDescription());
			$pageForm->getElement('meta_keywords')->setValue($pageObj->getMetaKeywords());
			$pageForm->getElement('short_description')->setValue($pageObj->getShortDescription());
			$pageForm->getElement('targetedKeyPhrase')->setValue($pageObj->getTargetedKeyPhrase());
			$categoryData = $this->_model->selectCategoryById($pageObj->getCategoryId());
			if($categoryData) {
				if($categoryData->id_parent == 0) {
					$pageForm->getElement('iscategory')->setValue(1);
				}
				else {
					$pageForm->getElement('iscategory')->setValue(0);
					$pageForm->getElement('pageselectcategory')->setValue($categoryData->id_parent);
				}
			}
			//set selected show in menu dropdown option
			$pageForm->getElement('selectmenu')->setValue($pageObj->getShowInMenu());
			//set template_id in a hidden field
			$pageForm->getElement('template_id')->setValue($pageObj->getTemplateId());
			//name the submit button.
			$pageForm->getElement('submit')->setLabel("{%UPDATE PAGE%}");

			//get new template for page using new template_id
			$templateObj  = new RCMS_Object_Template_Template($pageObj->getTemplateId());
			//setting correct name if it exists
			if($templateObj->getName()) {
				$templateName = ucfirst(strtolower(trim($templateObj->getName())));
			}else {
				$templateName = "Select a template.";
			}
			//set selected template name on a form.
			$pageForm->getElement('template_name')->setValue($templateName);

			$categories    = $this->_addSignToProtectedNames($this->_model->selectAllCategories());
			unset($categories[-1]);
			$categories = array('-1'=>"Select a category") + $categories;

			if(array_search($pageObj->getNavName(), $categories)) {
				unset($categories[array_search($pageObj->getNavName(), $categories)]);
			}
			$pageForm->getElement('pageselectcategory')->setMultiOptions($categories);
			$pageForm->getElement('selectmenu')->setMultiOptions($this->generateShowInMainMenuSelectData());

			if($pageObj->getUrl() == 'index') {
				$this->_setReadOnly($pageForm, 'url');
			}
			elseif($pageObj->getUrl() == RCMS_Object_QuickConfig_QuickConfig::$draftCategoryUrl) {
				$this->_setReadOnly($pageForm, 'url');
				$this->_setReadOnly($pageForm, 'nav_name');
				$this->_setReadOnly($pageForm, 'h1');
				$this->_setReadOnly($pageForm, 'header_title');
				$this->_hideElement($pageForm, 'iscategory');
				$this->_hideElement($pageForm, 'selectmenu');
			}
			return $pageForm;
		}
		return null;

	}

	private function _addSignToProtectedNames($protectedNames) {
		$protectedCategoriesNames = $this->_model->selectProtectedCategoriesNames();
		$protectedPagesNames = $this->_model->selectProtectedPagesNames();
		if(is_string($protectedNames)) {
			if(in_array($protectedNames, $protectedCategoriesNames) || in_array($protectedNames, $protectedPagesNames)) {
				return RCMS_Object_Page_Page::PROTECTED_SIGN . $protectedNames;
			}
		}
        if (is_array($protectedNames) && count($protectedNames) > 0) {
            foreach($protectedNames as $key => $protectedName) {
                if(in_array($protectedName, $protectedCategoriesNames) || in_array($protectedName, $protectedPagesNames)) {
                    $protectedNames[$key] = RCMS_Object_Page_Page::PROTECTED_SIGN . $protectedName;
                }
            }
        }
		return $protectedNames;
	}

	private function _setReadOnly($pageForm, $value) {
		$pageForm->getElement($value)->setAttrib('readonly','readonly');
		$pageForm->getElement($value)->setAttrib('style','background-color:#CCCCCC;');
	}

	private function _hideElement($pageForm, $value) {
		$pageForm->getElement($value)->setAttrib('style','display:none;');
	}


	/**
	 * @method This method generates data for select menu dropdown
	 * @return array
	 */
	public function generateShowInMainMenuSelectData() {
		return array(
			1 => '',
			2 => '',
			0 => ''
		);
	}

	/**
	 * This method deletes page
	 *
	 * @return void
	 */
	public function deletepageAction() {
		$websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;

		$pageId = $this->getRequest()->getParam('pageId');
		if($pageId>0) {
			$pageObj = new RCMS_Object_Page_Page($pageId);
			if($pageObj->getUrl()!='index') {
				if(!$this->getCategoryChildren($pageObj->getCategoryId())) {
					if($pageObj->delete()) {

						$imagesArray = $this->_model->selectPageImagesByPageId($pageObj->getId());
						if($imagesArray) {

							foreach ($imagesArray as $imageObj) {
								$pathImage = (string) $this->_config->website->website->path .'previews/'.$imageObj->name;
								$flagDelete =  RCMS_Tools_FilesystemTools::deleteFile($pathImage);
							}
						}
						//delete all images concerned page from the database
						$pageObj->deleteAllImages();

						//delete content of container for a page
						$containersIdArray = $this->_model->selectContainerIdsForPageByPageId($pageObj->getId());
						foreach ($containersIdArray as $container) {
							$this->_model->deleteContentByIdContainer($container['id']);
							//delete conainer's dependencies
							$this->_model->deleteContainerDependencies($container['id']);
						}

						//delete deeplinks dependencies
						$this->_model->deleteDeeplinksDependencies($this->getWebSiteUrl() . $pageObj->getUrl() . '.html');
						//delete all containers
						$this->_model->deleteContainerByPageId($pageObj->getId());
						//delete all categories
						$this->_model->deleteCategoryById($pageObj->getCategoryId());
						//delete all featured areas
						$this->_model->deleteFeaturedAreasByPageId($pageObj->getId());
						//on index page for now
						$this->_redirectSuccessDelete($websiteUrl);
					}else {
						$this->view->message="Problems with deleting. Check if page exists";
					}
				}else {
					$this->_session->cantDelete = true;
					$this->_redirect($websiteUrl.$pageObj->getUrl().".html");
				}
			}else {
				$this->_redirect($websiteUrl);
			}

		}else {
			$this->_redirect($websiteUrl);
		}
	}

	/**
	 * @method This method is getting children pages of a category.
	 *
	 * @param integer $categoryId
	 * @return array or boolean
	 */
	public function getCategoryChildren($categoryId) {
		if($categoryId>0) {
			$category = $this->_model->selectCategoryById($categoryId);
			if($category->id_parent==0) {
				$result = $this->_model->selectAllCategories($categoryId);
				if($result) {
					return $result;
				}else {
					return false;
				}
			}
			else {
				return false;
			}
		}
		return false;
	}

	/**
	 * @method This method is executing redirect after page delete action.
	 *
	 * @param String $url
	 */
	private function _redirectSuccessDelete($url) {
		$this->_redirect($url);
	}

	/**
	 * @method This method is processing errors from Page Form
	 *
	 * @param Array $array
	 * @return String $htmlUl
	 */
	public function processErrors($array) {
		$messages = array();
		$htmlUl = "";
		foreach ($array as $key => $value) {
			switch ($key) {
				case 'h1':
					if(isset($value['isEmpty']))
						$messages[]="H1 Tag field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="H1 Tag field can only contain letters,digits and '-' .";
					break;

				case 'header_title':
					if(isset($value['isEmpty']))
						$messages[]="Header Title field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Header Title field can only contain letters,digits and '-' .";
					break;

				case 'url':
					if(isset($value['isEmpty']))
						$messages[]="Url Address field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Url Address field can only contain letters,digits and '-' .";
					break;

				case 'nav_name':
					if(isset($value['isEmpty']))
						$messages[]="Navigation Name field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Navigation Name field can only contain letters,digits and '-' .";
					break;

				case 'meta_description':
					if(isset($value['stringLengthTooShort']))
						$messages[]="Meta description field is too short.";
					if(isset($value['stringLengthTooLong']))
						$messages[]="Meta description field is too long.";
					break;

				case 'meta_keywords':
					if(isset($value['stringLengthTooShort']))
						$messages[]="Meta keywords field is too short.";
					if(isset($value['stringLengthTooLong']))
						$messages[]="Meta keywords field is too long.";
					break;

				case 'short_description':
					if(isset($value['stringLengthTooShort']))
						$messages[]="Page description field is too short.";
					if(isset($value['stringLengthTooLong']))
						$messages[]="Page description field is too long.";
					break;
				case 'template':
					$messages[] = "Please select template for your page";
					break;
			}
		}

		if(!empty($messages)) {
			$htmlUl = "";
			foreach ($messages as $message) {
				$htmlUl .= "<li><strong>".$message."</strong></li>";
			}
			return $htmlUl;
		}
		return null;
	}

	/**
	 * @method Checks if page is a category
	 * @param Integer $categoryId
	 * @return Boolean
	 */
	public function isCategory($categoryId) {
		if(intval($categoryId)>0) {
			$categoryObj = $this->_model->selectCategoryById($categoryId);
			if($categoryObj->id_parent==0) {
				return true;
			}
		}else {
			return false;
		}
		return false;

	}


	public function listallAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$catPages = $this->_model->getPagesCategories();
		foreach ($catPages as $key => $catPage) {
			$catPages[$key]['navigationTitle'] = $this->_addSignToProtectedNames($catPage['navigationTitle']);
			$catPages[$key]['pages'] = $this->_model->getPagesForCategory($catPage['categoryId']);
			if(!empty ($catPages[$key]['pages'])) {
				foreach ($catPages[$key]['pages'] as $pkey => $pageData) {
					$catPages[$key]['pages'][$pkey]['navigationTitle'] = $this->_addSignToProtectedNames($pageData['navigationTitle']);
				}
			}
		}
		$staticMenuPages = $this->_model->getStaicMenuPages();
		if(!empty ($staticMenuPages)) {
			foreach ($staticMenuPages as $key => $statPageData) {
				$staticMenuPages[$key]['navigationTitle'] = $this->_addSignToProtectedNames($statPageData['navigationTitle']);
			}
			$this->view->staticPages = $staticMenuPages;
		}
		$noMenuPages = $this->_model->getNoMenuPages();
		if(!empty($noMenuPages)) {
			foreach ($noMenuPages as $key => $nomenuPageData) {
				$noMenuPages[$key]['navigationTitle'] = $this->_addSignToProtectedNames($nomenuPageData['navigationTitle']);
			}
			$this->view->nomenuPages = $noMenuPages;
		}
		$this->view->pages = $catPages;

		$homePageId = $this->_model->getHomePageId();

		$this->view->homePageId = $homePageId;
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}


	/**
	 *@method  Recive order array and do the order routine
	 */
	public function orderAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		$ordersArray = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('orderList')));
        $staticOrderList = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('staticOrderList')));
        $noMenuList = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('nomenuList')));
		if(!empty ($ordersArray)) {
			foreach ($ordersArray as $arrayItem) {
				if($arrayItem->pageId) {
					$category = new RCMS_Object_Page_Page($arrayItem->pageId);
					//$category->setUrl(urldecode($category->getUrl()));
					$category->setOrder($arrayItem->order);
					$catSaved = $category->save();
					$subPages = $arrayItem->pages;
					if(!empty ($subPages)) {
						foreach ($subPages as $subPage) {
							if($subPage->id) {
								$categoryPage = new RCMS_Object_Page_Page($subPage->id);
								//$categoryPage->setUrl(urldecode($categoryPage->getUrl()));
								$categoryPage->setOrder($subPage->order);
								$categoryPage->setParentCategory($category->getCategoryId());
								$categoryPage->setShowInMenu(1);
								$catPageSaved = $categoryPage->save();
							}
						}
					}
				}
			}
		}
		
        if(!empty ($staticOrderList)) {
            foreach ($staticOrderList as $statOrderItem) {
				if($statOrderItem->id) {
					$statPage = new RCMS_Object_Page_Page($statOrderItem->id);
				//	$statPage->setUrl(urldecode($statPage->getUrl()));
					$statPage->setStaticOrder($statOrderItem->order);
					$statPage->setParentCategory(-1);
					$statPage->setShowInMenu(2);
					$statSaved = $statPage->save();
				}
            }
        }
		if(!empty($noMenuList)) {
			foreach ($noMenuList as $noMenuItem) {
				if($noMenuItem->id) {
					$nomPage = new RCMS_Object_Page_Page($noMenuItem->id);
					//$nomPage->setUrl(urldecode($nomPage->getUrl()));
					$nomPage->setShowInMenu(0);
					$nomPage->setParentCategory(-1);
					$nomPage->save();
				}
            }
        }
		
        if((isset($catSaved) && $catSaved) || (isset($statSaved) && $statSaved))  {
            echo 'success';
            exit;
        }
        echo "failed";
        exit;
    }

	/**
	 *@method Edit page h1 tag from listallpages
	 *
	 */
	public function edithtagAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$pageId = intval($this->getRequest()->getParam('pageId'));
		$newH1 = $this->getRequest()->getParam('newH1');
		$page = new RCMS_Object_Page_Page($pageId);
		$oldH1 = $page->getH1Tag();
		if($oldH1 != $newH1) {
			$page->setH1Tag($newH1);
			if($page->save()) {
				$this->_seoParser->chainSyncOnUpdate($page->getUrl(), $page->getUrl(), $page->getH1Tag(), $page->getId());
				$this->_seoParser->createSiteMapFile();
				echo $newH1;
				exit;
			}
			echo 'Error. Can not save page.';
			exit;
		}
		echo $oldH1;
		exit;
	}

	/**
	 *@method Edit edit keywords action
	 *
	 */
	public function editkeywordsAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$pageId = intval($this->getRequest()->getParam('pageId'));
		$newKeys = strip_tags($this->getRequest()->getParam('newKeys'));
		$page = new RCMS_Object_Page_Page($pageId);
		$page->setMetaKeywords($newKeys);
		if($page->save()) {
			echo $newKeys;
			exit;
		}
		echo 'Error. Can not save page.';
		exit;
	}

	/**
	 * @method Regenerates menu according to page (category / not category) (AJAX called in views/scripts/addpage.phtml)
	 *
	 */
	public function regeneratemenuAction() {
		$initMenu = 'all';
		$isCat = $this->getRequest()->getParam('iscat');
		if($isCat == 'true') {
			echo 'main';
		}
		elseif($isCat == 'false') {
			echo $initMenu;
		}
		exit;
	}

	/**
	 * @method checks not found
	 *
	 */
	public function checkoptAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$pageTypeToCheck = $this->getRequest()->getParam('type');
		$result = $this->_model->selectOptPage($pageTypeToCheck);
		echo (!empty($result)) ? urlencode($result) : 'fail';
	}

	/**
	 * @method updates not found
	 *
	 */
	public function updateoptAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$pageUrl = $this->getRequest()->getParam('pageUrl');
		$pageOptState = $this->getRequest()->getParam('newVal');
		$pageType = $this->getRequest()->getParam('type');
		return $this->_model->updatePageOptState($pageUrl, $pageOptState, $pageType);
	}

	public function proccessUrl($url,$search=' ',$replace='-') {
		$url = str_replace(".html", '',trim($url));
		return str_replace($search, $replace,$url);
	}

	public function massdeletepagesAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$result1 = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('result1')));
			$result2 = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('result2')));
			$result3 = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('result3')));

			$common = array();
			foreach ($result1 as $value) {
				if($value!='0') {
					$common[] = str_replace("page-","",$value);
				}
			}

			foreach ($result2 as $value) {
				if($value!='0') {
					$common[]=str_replace("page-","",$value);
				}
			}

			foreach ($result3 as $value) {
				if($value!='0') {
					$common[]= str_replace("page-","",$value);
				}
			}
			
			foreach ($common as $value) {
				$pageObj = new RCMS_Object_Page_Page($value);
				if($pageObj->getUrl()!='index') {
					if(!$this->getCategoryChildren($pageObj->getCategoryId())) {
						if($pageObj->delete()) {
							$imagesArray = $this->_model->selectPageImagesByPageId($pageObj->getId());
							if($imagesArray) {

								foreach ($imagesArray as $imageObj) {
									$pathImage = (string) $this->_config->website->website->path .'previews/'.$imageObj->name;
									$flagDelete =  RCMS_Tools_FilesystemTools::deleteFile($pathImage);
								}
							}
							//delete all images concerned page from the database
							$pageObj->deleteAllImages();

							//delete content of container for a page
							$containersIdArray = $this->_model->selectContainerIdsForPageByPageId($pageObj->getId());
							foreach ($containersIdArray as $container) {
								$this->_model->deleteContentByIdContainer($container['id']);
								//delete conainer's dependencies
								$this->_model->deleteContainerDependencies($container['id']);
							}
							//delete deeplinks dependencies
							$this->_model->deleteDeeplinksDependencies($this->getWebSiteUrl() . $pageObj->getUrl() . '.html');
							//delete all containers
							$this->_model->deleteContainerByPageId($pageObj->getId());
							//delete all categories
							$this->_model->deleteCategoryById($pageObj->getCategoryId());
							//delete all featured areas
							$this->_model->deleteFeaturedAreasByPageId($pageObj->getId());
						//on index page for now
						//$this->_redirectSuccessDelete($websiteUrl);
						}
					}
				}
			}
/*
			foreach ($common as $value) {
				$pageObj = new RCMS_Object_Page_Page($value);
				$pageObj->delete();
			}*/
			echo RCMS_Tools_Tools::stripSlashesIfQuotesOn(json_encode($common));
		}
	}

     public function statAction()
     {
         $this->_helper->getHelper('layout')->disableLayout();
         $this->_helper->viewRenderer->setNoRender(true);
         if ($this->getRequest()->isPost())
         {
            $url = $this->getRequest()->getParam('url');
            $key = $this->getRequest()->getParam('key');
            if (!empty($url) && !empty($key)){
                $sepos  = new RCMS_Object_SEPosition_SEPosition($url, $key);
                $sepos->run();
                print_r($sepos->showStatistic($url));
            }


         }
     }

	 /**
	  * Save additional page options such as is page 404 Not found page, is page protected, etc.. (AJAX. Called in page.js)
	  *
	  * @return boolean
	  */
	 public function saveaoptsAction() {
		 $this->_helper->getHelper('layout')->disableLayout();
         $this->_helper->viewRenderer->setNoRender(true);
		 if($this->getRequest()->isPost()) {
			 $options = $this->getRequest()->getParam('opts');
			 $allOptions = $this->getRequest()->getParam('allOpts');
			 $options = array_intersect($options, $allOptions);
			 $addOptions = array();
			 if(!is_array($options) || empty ($options)) {
				$addOptions[RCMS_Object_Page_Page::P_OPT_404PAGE]          = false;
				$addOptions[RCMS_Object_Page_Page::P_OPT_PROTECTED]        = false;
				$addOptions[RCMS_Object_Page_Page::P_OPT_MEMLANDING]       = false;
				$addOptions[RCMS_Object_Page_Page::P_OPT_PRODCATLANDING]   = false;
				$addOptions[RCMS_Object_Page_Page::P_OPT_PRODBRANDLANDING] = false;
			 }
			 else {
				 foreach ($options as $option) {
					switch ($option) {
						case RCMS_Object_Page_Page::P_OPT_404PAGE:
							$addOptions[RCMS_Object_Page_Page::P_OPT_404PAGE] = true;
						break;
						case RCMS_Object_Page_Page::P_OPT_PROTECTED:
							$addOptions[RCMS_Object_Page_Page::P_OPT_PROTECTED] = true;
						break;
						case RCMS_Object_Page_Page::P_OPT_MEMLANDING:
							$addOptions[RCMS_Object_Page_Page::P_OPT_MEMLANDING] = true;
						break;
						case RCMS_Object_Page_Page::P_OPT_PRODCATLANDING:
							$addOptions[RCMS_Object_Page_Page::P_OPT_PRODCATLANDING] = true;
						break;
						case RCMS_Object_Page_Page::P_OPT_PRODBRANDLANDING:
							$addOptions[RCMS_Object_Page_Page::P_OPT_PRODBRANDLANDING] = true;
						break;
					}
				 }
			 }
			 $this->_session->additionalOptions = $addOptions;
			 $this->getResponse()->setBody(RCMS_Object_QuickConfig_QuickConfig::AJX_RESP_SUCCESS)->sendResponse();
			 exit;
		 }
	 }

	 private function _addOptionsToPageData($pageData) {
		$additionalOptions = $this->_session->additionalOptions;
		if(!$additionalOptions) {
			$additionalOptions = array(
				$addOptions[RCMS_Object_Page_Page::P_OPT_PROTECTED] = $pageData['protected']
			);
		}
		if(is_array($additionalOptions)) {
			$pageData = array_merge($pageData, $additionalOptions);
		}
		return $pageData;
	 }

	 private function _generateOptionsString(RCMS_Object_Page_Page $page) {
		 if(!$page instanceof RCMS_Object_Page_Page) {
			 return '{%no options yet%}';
		 }
		 $optString = '';
		 $opt = array();
		 if($page->getIs404Page()) {
			 $opt[] = '{%404 page%}';
		 }
		 if($page->getProtected()) {
			 $opt[] = '{%protected%}';
		 }
		 if($page->getMemLandig()) {
			 $opt[] = '{%member landig page%}';
		 }
		 if($page->getProdBrandLand()) {
			 $opt[] = '{%product brand landig page%}';
		 }
		 if($page->getProdCatLand()) {
			 $opt[] = '{%product category landig page%}';
		 }
		 if(empty ($opt)) {
			 return '{%no options yet%}';
		 }
		 foreach ($opt as $option) {
			 $optString .= $option . ', ';
		 }
		 return rtrim($optString, ', ');
	 }
}

